package com.example.neutonote2.ui.notes;

import android.app.DatePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.SavedStateHandle;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.example.neutonote2.R;
import com.example.neutonote2.data.model.Category;
import com.example.neutonote2.data.model.Note;
import com.example.neutonote2.data.model.NoteWithTags;
import com.example.neutonote2.data.model.Tag;
import com.example.neutonote2.utils.DeepseekUtils;
import com.example.neutonote2.viewmodel.CategoryViewModel;
import com.example.neutonote2.viewmodel.NoteViewModel;
import com.example.neutonote2.viewmodel.TagViewModel;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.example.neutonote2.databinding.FragmentNoteEditBinding;
import com.example.neutonote2.MainActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class NoteEditFragment extends Fragment {

    private NoteViewModel noteViewModel;
    private TagViewModel tagViewModel;
    private CategoryViewModel categoryViewModel;

    private EditText editTitle;
    private EditText editContent;
    private Spinner spinnerCategory;
    private RadioGroup radioGroupReview;
    private Button btnSetReviewDate;
    private Button btnSaveNote;
    private Button btnDeleteNote;
    private ChipGroup chipGroupTags;
    private MaterialButton btnAddTag;
    private MaterialButton btnFormatBold;
    private MaterialButton btnFormatItalic;
    private MaterialButton btnFormatHighlight;
    private FloatingActionButton fabSaveNote;
    private ProgressBar progressBar;
    private FrameLayout progressContainer;

    private int noteId = -1;
    private Note currentNote;
    private List<Tag> selectedTags = new ArrayList<>();
    private List<Tag> availableTags = new ArrayList<>();
    private List<Category> categories = new ArrayList<>();
    private Date nextReviewDate = null;

    private FragmentNoteEditBinding binding;
    private AppBarConfiguration appBarConfiguration;
    private View rootView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        if (getArguments() != null) {
            noteId = getArguments().getInt("noteId", -1);
        }
        
        // 处理物理返回按钮
        requireActivity().getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                // 直接返回到主页面
                NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment_content_main);
                navController.navigate(R.id.nav_all_notes);
            }
        });
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentNoteEditBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // 初始化视图绑定
        editTitle = binding.editNoteTitle;
        editContent = binding.editNoteContent;
        spinnerCategory = binding.spinnerCategory;
        chipGroupTags = binding.chipGroupTags;
        btnAddTag = binding.btnAddTag;
        btnSaveNote = binding.btnSaveNote;
        btnDeleteNote = binding.btnDeleteNote;
        fabSaveNote = binding.fabSaveNote;
        radioGroupReview = binding.radioGroupReview;
        btnSetReviewDate = binding.btnSetReviewDate;
        btnFormatBold = binding.btnFormatBold;
        btnFormatItalic = binding.btnFormatItalic;
        btnFormatHighlight = binding.btnFormatHighlight;
        progressBar = binding.progressBar;
        progressContainer = binding.progressContainer;

        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        rootView = view;

        // 初始化ViewModel
        noteViewModel = new ViewModelProvider(requireActivity()).get(NoteViewModel.class);
        tagViewModel = new ViewModelProvider(requireActivity()).get(TagViewModel.class);
        categoryViewModel = new ViewModelProvider(requireActivity()).get(CategoryViewModel.class);

        // 设置工具栏
        setupToolbar(view);

        // 设置格式化按钮
        setupFormatButtons();

        // 加载分类
        loadCategories();

        // 加载标签
        loadTags();

        // 设置保存按钮点击事件
        btnSaveNote.setOnClickListener(v -> saveNote());
        
        // 设置浮动保存按钮点击事件
        fabSaveNote.setOnClickListener(v -> saveNote());
        
        // 设置添加标签按钮点击事件
        btnAddTag.setOnClickListener(v -> showTagSelectionDialog());

        // 设置设置复习日期按钮点击事件
        btnSetReviewDate.setOnClickListener(v -> showDatePicker());
        
        // 设置删除按钮点击事件
        btnDeleteNote.setOnClickListener(v -> confirmDelete());

        // 如果是编辑模式，加载笔记数据
        if (noteId != -1) {
            // 加载笔记
            loadNoteData();
        } else {
            // 新建笔记初始化
            currentNote = new Note("", "", "");  // 使用有参构造函数，提供空字符串作为初始值
            currentNote.setCreatedTime(new Date());
            currentNote.setModifiedTime(new Date());
            currentNote.setReviewStatus("待复习");
            nextReviewDate = calculateDefaultReviewDate();
            updateReviewDateButtonText();
        }

        // 添加点击空白区域隐藏键盘的逻辑
        view.setOnTouchListener((v, event) -> {
            hideKeyboard();
            return false;
        });
        
        // 设置SavedStateHandle的监听器，接收AI功能标志
        setupSavedStateHandleObserver();
    }

    private void setupToolbar(View root) {
        Toolbar toolbar = root.findViewById(R.id.toolbar_note_edit);
        ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
        // 隐藏ActionBar的标题，避免重复显示
        ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);

        // 设置返回按钮点击事件
        toolbar.setNavigationOnClickListener(v -> {
            // 直接返回到主页面而不是上一级
            NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment_content_main);
            navController.navigate(R.id.nav_all_notes);
        });

        // 手动设置菜单
        toolbar.inflateMenu(R.menu.menu_note_edit);
        
        // 合并所有菜单点击处理
        toolbar.setOnMenuItemClickListener(item -> {
            int id = item.getItemId();
            if (id == R.id.action_delete) {
                confirmDelete();
                return true;
            } else if (id == R.id.action_extract_key_points) {
                extractKeyPoints();
                return true;
            } else if (id == R.id.action_add_tags) {
                showTagSelectionDialog();
                return true;
            } else if (id == R.id.action_summarize) {
                summarizeContent();
                return true;
            } else if (id == R.id.action_optimize) {
                optimizeNote();
                return true;
            } else if (id == R.id.action_ask) {
                askQuestionAboutNote();
                return true;
            } else if (id == R.id.action_save) {
                saveNote();
                return true;
            }
            return false;
        });
    }

    private void setupFormatButtons() {
        btnFormatBold.setOnClickListener(v -> formatSelectedText(android.graphics.Typeface.BOLD));
        btnFormatItalic.setOnClickListener(v -> formatSelectedText(android.graphics.Typeface.ITALIC));
        btnFormatHighlight.setOnClickListener(v -> highlightSelectedText());
    }

    private void loadCategories() {
        categoryViewModel.getAllCategories().observe(getViewLifecycleOwner(), categoryList -> {
            if (categoryList != null) {
                categories = categoryList;
                List<String> categoryNames = new ArrayList<>();
                for (Category category : categories) {
                    categoryNames.add(category.getName());
                }

                ArrayAdapter<String> adapter = new ArrayAdapter<>(
                        requireContext(),
                        android.R.layout.simple_dropdown_item_1line,
                        categoryNames);
                spinnerCategory.setAdapter(adapter);

                // 如果是编辑模式，设置选中的分类
                if (currentNote != null) {
                    String category = currentNote.getCategory();
                    for (int i = 0; i < categoryNames.size(); i++) {
                        if (categoryNames.get(i).equals(category)) {
                            spinnerCategory.setSelection(i);
                            break;
                        }
                    }
                }

                // 设置分类选择事件
                spinnerCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        if (currentNote != null) {
                            currentNote.setCategory(categoryNames.get(position));
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                    }
                });
            }
        });
    }

    private void loadTags() {
        tagViewModel.getAllTags().observe(getViewLifecycleOwner(), tagList -> {
            if (tagList != null) {
                availableTags = tagList;
            }
        });
    }

    private void loadNoteData() {
        Log.d("NoteEditFragment", "加载笔记数据，noteId=" + noteId);
        
        // 先获取笔记的基本信息
        noteViewModel.getNoteById(noteId).observe(getViewLifecycleOwner(), note -> {
            if (note != null) {
                Log.d("NoteEditFragment", "获取到笔记: " + note.getTitle());
                currentNote = note;
                
                // 更新基本UI（标题、内容、分类等）
                editTitle.setText(currentNote.getTitle());
                editContent.setText(currentNote.getContent());
                
                // 设置分类
                if (categories != null && !categories.isEmpty()) {
                    int position = getCategoryPosition(currentNote.getCategory());
                    spinnerCategory.setSelection(position);
                }
                
                // 设置复习状态
                String reviewStatus = currentNote.getReviewStatus();
                if ("已掌握".equals(reviewStatus)) {
                    radioGroupReview.check(R.id.radio_mastered);
                } else if ("需加强".equals(reviewStatus)) {
                    radioGroupReview.check(R.id.radio_need_strengthen);
                } else {
                    radioGroupReview.check(R.id.radio_to_review);
                }
                
                // 设置下次复习日期
                nextReviewDate = currentNote.getNextReviewDate();
                if (nextReviewDate == null) {
                    nextReviewDate = calculateDefaultReviewDate();
                }
                updateReviewDateButtonText();
            } else {
                Log.e("NoteEditFragment", "获取笔记失败，noteId=" + noteId);
            }
        });
        
        // 获取笔记的标签信息
        noteViewModel.getNoteWithTags(noteId).observe(getViewLifecycleOwner(), noteWithTags -> {
            if (noteWithTags != null && noteWithTags.tags != null) {
                Log.d("NoteEditFragment", "获取到笔记标签，数量: " + noteWithTags.tags.size());
                selectedTags = noteWithTags.tags;
                updateTagChips(selectedTags);
            } else {
                Log.d("NoteEditFragment", "笔记没有标签或获取失败");
                selectedTags = new ArrayList<>();
                updateTagChips();
            }
        });
    }

    private void updateTagChips(List<Tag> tags) {
        chipGroupTags.removeAllViews();
        for (Tag tag : tags) {
            addTagChip(tag);
        }
    }
    
    private void updateTagChips() {
        chipGroupTags.removeAllViews();
        for (Tag tag : selectedTags) {
            addTagChip(tag);
        }
    }

    private void addTagChip(Tag tag) {
        Chip chip = new Chip(requireContext());
        chip.setText(tag.getName());
        chip.setCloseIconVisible(true);
        chip.setCloseIconTintResource(android.R.color.white);
        try {
            int color = android.graphics.Color.parseColor(tag.getColor());
            chip.setChipBackgroundColor(android.content.res.ColorStateList.valueOf(color));
        } catch (IllegalArgumentException e) {
            // 如果颜色格式无效，使用默认颜色
            chip.setChipBackgroundColorResource(android.R.color.holo_blue_light);
        }
        chip.setTextColor(android.graphics.Color.BLACK);

        chip.setOnCloseIconClickListener(v -> {
            selectedTags.remove(tag);
            chipGroupTags.removeView(chip);
        });

        chipGroupTags.addView(chip);
    }

    private void showTagSelectionDialog() {
        // 1. Filter availableTags to exclude error messages or invalid tags
        List<Tag> validDisplayTags = new ArrayList<>();
        if (availableTags != null) {
            for (Tag tag : availableTags) {
                if (tag != null && tag.getName() != null &&
                    !tag.getName().toLowerCase().contains("unable to resolve host") && 
                    !tag.getName().toLowerCase().contains("no address associated with hostname")) {
                    validDisplayTags.add(tag);
                }
            }
        }

        // 2. Check if there are any valid tags to display
        if (validDisplayTags.isEmpty()) {
            Toast.makeText(requireContext(), "没有可用的标签。", Toast.LENGTH_SHORT).show();
            return;
        }

        // 3. Prepare items for the dialog based on validDisplayTags
        List<String> displayTagNames = new ArrayList<>();
        boolean[] checkedStatus = new boolean[validDisplayTags.size()];

        for (int i = 0; i < validDisplayTags.size(); i++) {
            Tag currentDisplayTag = validDisplayTags.get(i);
            displayTagNames.add(currentDisplayTag.getName());
            // Check if this valid display tag is already in the selectedTags list by ID
            checkedStatus[i] = selectedTags.stream()
                                          .anyMatch(st -> st.getId() == currentDisplayTag.getId());
        }

        // 4. Build and show the dialog
        new MaterialAlertDialogBuilder(requireContext())
                .setTitle("选择标签")
                .setMultiChoiceItems(displayTagNames.toArray(new String[0]), checkedStatus,
                        (dialog, which, isChecked) -> {
                            checkedStatus[which] = isChecked;
                        })
                .setPositiveButton("确定", (dialog, which) -> {
                    selectedTags.clear(); // Start fresh with selections from this dialog
                    for (int i = 0; i < validDisplayTags.size(); i++) { // Iterate through the tags shown in dialog
                        if (checkedStatus[i]) { // If this tag was checked
                            selectedTags.add(validDisplayTags.get(i)); // Add it
                        }
                    }
                    updateTagChips(); // Refresh the UI
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void formatSelectedText(int style) {
        int start = editContent.getSelectionStart();
        int end = editContent.getSelectionEnd();

        if (start < end) {
            Spannable spannable = new SpannableStringBuilder(editContent.getText());
            spannable.setSpan(new StyleSpan(style), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            editContent.setText(spannable);
            editContent.setSelection(end);
        }
    }

    private void highlightSelectedText() {
        int start = editContent.getSelectionStart();
        int end = editContent.getSelectionEnd();

        if (start < end) {
            Spannable spannable = new SpannableStringBuilder(editContent.getText());
            spannable.setSpan(new BackgroundColorSpan(android.graphics.Color.YELLOW), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            editContent.setText(spannable);
            editContent.setSelection(end);
        }
    }

    private void saveNote() {
        // 隐藏键盘
        hideKeyboard();
        
        String title = editTitle.getText().toString().trim();
        String content = editContent.getText().toString().trim();
        String category = spinnerCategory.getSelectedItem().toString();

        if (title.isEmpty()) {
            Toast.makeText(requireContext(), "请输入标题", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取复习状态
        String reviewStatus;
        int radioButtonId = radioGroupReview.getCheckedRadioButtonId();
        if (radioButtonId == R.id.radio_mastered) {
            reviewStatus = "已掌握";
        } else if (radioButtonId == R.id.radio_need_strengthen) {
            reviewStatus = "需加强";
        } else {
            reviewStatus = "待复习";
        }

        if (currentNote == null) {
            currentNote = new Note(title, content, category);
        } else {
            currentNote.setTitle(title);
            currentNote.setContent(content);
            currentNote.setCategory(category);
        }

        currentNote.setReviewStatus(reviewStatus);
        currentNote.setNextReviewDate(nextReviewDate);

        if (noteId == -1) {
            // 新建笔记
            noteViewModel.insertNoteWithTags(currentNote, selectedTags);
        } else {
            // 更新笔记
            noteViewModel.updateNoteWithTags(currentNote, selectedTags);
        }

        // 直接返回到主页面
        NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment_content_main);
        navController.navigate(R.id.nav_all_notes);
    }

    private void showDatePicker() {
        Calendar calendar = Calendar.getInstance();
        if (nextReviewDate != null) {
            calendar.setTime(nextReviewDate);
        }

        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(requireContext(),
                (view, selectedYear, selectedMonth, selectedDay) -> {
                    calendar.set(selectedYear, selectedMonth, selectedDay);
                    nextReviewDate = calendar.getTime();
                    updateReviewDateButtonText();
                }, year, month, day);

        datePickerDialog.show();
    }

    private void updateReviewDateButtonText() {
        if (nextReviewDate != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            String dateString = dateFormat.format(nextReviewDate);
            btnSetReviewDate.setText("复习日期: " + dateString);
        } else {
            btnSetReviewDate.setText(R.string.set_review_date);
        }
    }

    private Date calculateDefaultReviewDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 3); // 默认3天后复习
        return calendar.getTime();
    }

    private void confirmDelete() {
        if (noteId == -1) {
            // 新建笔记模式，直接返回笔记列表
            Toast.makeText(requireContext(), "笔记未保存，已取消", Toast.LENGTH_SHORT).show();
            NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment_content_main);
            navController.navigate(R.id.nav_all_notes);
            return;
        }
        
        // 编辑已有笔记模式
        new AlertDialog.Builder(requireContext())
                .setTitle("删除笔记")
                .setMessage("确定要删除这个笔记吗？")
                .setPositiveButton("删除", (dialog, which) -> {
                    noteViewModel.deleteById(noteId);
                    // 直接返回到主页面
                    NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment_content_main);
                    navController.navigate(R.id.nav_all_notes);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    /**
     * 提取重点
     */
    private void extractKeyPoints() {
        if (!DeepseekUtils.isApiKeySet(requireContext())) {
            Toast.makeText(requireContext(), "请先在设置中配置DeepSeek API密钥", Toast.LENGTH_LONG).show();
            return;
        }
        
        String content = editContent.getText().toString().trim();
        if (content.isEmpty()) {
            Toast.makeText(requireContext(), "请先输入笔记内容", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 显示进度条
        progressContainer.setVisibility(View.VISIBLE);
        
        // 创建笔记对象用于API调用
        NoteWithTags noteWithTags = new NoteWithTags();
        if (currentNote == null) {
            String title = editTitle.getText().toString().trim();
            String category = spinnerCategory.getSelectedItem().toString();
            noteWithTags.note = new Note(title, content, category);
        } else {
            noteWithTags.note = currentNote;
        }
        noteWithTags.tags = selectedTags;
        
        // 调用API提取重点 - 使用beta/completions API
        DeepseekUtils.processNoteAsync(
                requireContext(),
                noteWithTags,
                "请从这篇笔记中提取5-10个关键要点，以要点列表形式返回",
                false, // 使用beta API
                new DeepseekUtils.ApiCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        progressContainer.setVisibility(View.GONE);
                        showKeyPointsDialog(result);
                    }

                    @Override
                    public void onFailure(String error) {
                        progressContainer.setVisibility(View.GONE);
                        Toast.makeText(requireContext(), error, Toast.LENGTH_LONG).show();
                    }
                });
    }
    
    /**
     * 显示关键点对话框
     */
    private void showKeyPointsDialog(String keyPoints) {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_key_points, null);
        TextView textKeyPoints = dialogView.findViewById(R.id.text_key_points);
        textKeyPoints.setText(keyPoints);
        
        new MaterialAlertDialogBuilder(requireContext())
            .setTitle("笔记重点")
            .setView(dialogView)
            .setPositiveButton("添加到笔记", (dialog, which) -> {
                // 将关键点添加到笔记内容末尾
                String currentContent = editContent.getText().toString();
                String newContent = currentContent + "\n\n【重点】\n" + keyPoints;
                editContent.setText(newContent);
            })
            .setNegativeButton("关闭", null)
            .show();
    }

    // 添加隐藏键盘的方法
    private void hideKeyboard() {
        View view = getActivity().getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            view.clearFocus();
        }
    }

    /**
     * 显示AI助手菜单
     */
    private void showAiMenu() {
        if (!DeepseekUtils.isApiKeySet(requireContext())) {
            Toast.makeText(requireContext(), "请先在设置中配置DeepSeek API密钥", Toast.LENGTH_LONG).show();
            return;
        }
        
        String[] options = {"生成摘要", "智能优化笔记", "提问笔记内容", "提取重点"};
        
        new MaterialAlertDialogBuilder(requireContext())
            .setTitle("AI助手")
            .setItems(options, (dialog, which) -> {
                switch (which) {
                    case 0:
                        summarizeContent();
                        break;
                    case 1:
                        optimizeNote();
                        break;
                    case 2:
                        askQuestionAboutNote();
                        break;
                    case 3:
                        extractKeyPoints();
                        break;
                }
            })
            .show();
    }
    
    /**
     * 生成摘要
     */
    private void summarizeContent() {
        String content = editContent.getText().toString().trim();
        if (content.isEmpty()) {
            Toast.makeText(requireContext(), "请先输入笔记内容", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 显示进度条
        progressContainer.setVisibility(View.VISIBLE);
        
        // 调用API生成摘要
        DeepseekUtils.summarizeNoteAsync(requireContext(), content, 
                new DeepseekUtils.ApiCallback<String>() {
                    @Override
                    public void onSuccess(String summary) {
                        progressContainer.setVisibility(View.GONE);
                        showSummaryDialog(summary);
                    }

                    @Override
                    public void onFailure(String error) {
                        progressContainer.setVisibility(View.GONE);
                        Toast.makeText(requireContext(), error, Toast.LENGTH_LONG).show();
                    }
                });
    }
    
    /**
     * 显示摘要对话框
     */
    private void showSummaryDialog(String summary) {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_summary, null);
        TextView textSummary = dialogView.findViewById(R.id.text_summary);
        textSummary.setText(summary);
        
        new MaterialAlertDialogBuilder(requireContext())
            .setTitle("内容摘要")
            .setView(dialogView)
            .setPositiveButton("添加到笔记", (dialog, which) -> {
                // 将摘要添加到笔记内容开头
                String currentContent = editContent.getText().toString();
                String newContent = "【摘要】" + summary + "\n\n" + currentContent;
                editContent.setText(newContent);
            })
            .setNegativeButton("关闭", null)
            .show();
    }
    
    /**
     * 优化笔记
     */
    private void optimizeNote() {
        String content = editContent.getText().toString().trim();
        if (content.isEmpty()) {
            Toast.makeText(requireContext(), "请先输入笔记内容", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 自动选中所有笔记内容
        editContent.requestFocus();
        editContent.selectAll();
        
        // 显示进度条
        progressContainer.setVisibility(View.VISIBLE);
        
        // 创建笔记对象用于API调用
        NoteWithTags noteWithTags = new NoteWithTags();
        noteWithTags.note = currentNote;
        noteWithTags.tags = selectedTags;
        
        // 调用API优化笔记 - 使用beta/completions API
        DeepseekUtils.processNoteAsync(
                requireContext(),
                noteWithTags,
                "请优化以下笔记内容，提高其清晰度和可读性，保持原意的同时改进结构和表达",
                false, // 使用beta API
                new DeepseekUtils.ApiCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        progressContainer.setVisibility(View.GONE);
                        showOptimizedNoteDialog(result);
                    }

                    @Override
                    public void onFailure(String error) {
                        progressContainer.setVisibility(View.GONE);
                        Toast.makeText(requireContext(), error, Toast.LENGTH_LONG).show();
                    }
                });
    }
    
    /**
     * 显示优化后的笔记对话框
     */
    private void showOptimizedNoteDialog(String optimizedContent) {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_optimized_note, null);
        TextView textOptimizedContent = dialogView.findViewById(R.id.text_optimized_content);
        textOptimizedContent.setText(optimizedContent);
        
        new MaterialAlertDialogBuilder(requireContext())
            .setTitle("优化后的笔记")
            .setView(dialogView)
            .setPositiveButton("使用优化版本", (dialog, which) -> {
                editContent.setText(optimizedContent);
            })
            .setNegativeButton("取消", null)
            .show();
    }
    
    /**
     * 提问笔记内容
     */
    private void askQuestionAboutNote() {
        String content = editContent.getText().toString().trim();
        if (content.isEmpty()) {
            Toast.makeText(requireContext(), "请先输入笔记内容", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 显示提问对话框
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_ask_question, null);
        EditText editQuestion = dialogView.findViewById(R.id.edit_question);
        
        AlertDialog dialog = new MaterialAlertDialogBuilder(requireContext())
            .setTitle("向AI提问")
            .setView(dialogView)
            .setPositiveButton("提问", null)
            .setNegativeButton("取消", null)
            .create();
        
        dialog.setOnShowListener(dialogInterface -> {
            Button button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
            button.setOnClickListener(view -> {
                String question = editQuestion.getText().toString().trim();
                if (question.isEmpty()) {
                    Toast.makeText(requireContext(), "请输入问题", Toast.LENGTH_SHORT).show();
                    return;
                }
                
                // 隐藏对话框并显示进度条
                dialog.dismiss();
                progressContainer.setVisibility(View.VISIBLE);
                
                // 创建笔记对象用于API调用
                NoteWithTags noteWithTags = new NoteWithTags();
                noteWithTags.note = currentNote;
                noteWithTags.tags = selectedTags;
                
                // 调用API回答问题 - 使用chat/completions API
                DeepseekUtils.processNoteAsync(
                        requireContext(),
                        noteWithTags,
                        question,
                        true, // 使用chat API
                        new DeepseekUtils.ApiCallback<String>() {
                            @Override
                            public void onSuccess(String answer) {
                                progressContainer.setVisibility(View.GONE);
                                showAnswerDialog(question, answer);
                            }

                            @Override
                            public void onFailure(String error) {
                                progressContainer.setVisibility(View.GONE);
                                Toast.makeText(requireContext(), error, Toast.LENGTH_LONG).show();
                            }
                        });
            });
        });
        
        dialog.show();
    }
    
    /**
     * 显示回答对话框
     */
    private void showAnswerDialog(String question, String answer) {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_answer, null);
        TextView textQuestion = dialogView.findViewById(R.id.text_question);
        TextView textAnswer = dialogView.findViewById(R.id.text_answer);
        
        textQuestion.setText(question);
        textAnswer.setText(answer);
        
        new MaterialAlertDialogBuilder(requireContext())
            .setTitle("AI回答")
            .setView(dialogView)
            .setPositiveButton("添加到笔记", (dialog, which) -> {
                // 将问答添加到笔记末尾
                String currentContent = editContent.getText().toString();
                String newContent = currentContent + "\n\n【问】" + question + "\n【答】" + answer;
                editContent.setText(newContent);
            })
            .setNegativeButton("关闭", null)
            .show();
    }

    /**
     * 设置SavedStateHandle的监听器，接收AI功能标志
     */
    private void setupSavedStateHandleObserver() {
        NavController navController = Navigation.findNavController(requireActivity(), R.id.nav_host_fragment_content_main);
        
        // 首先检查Bundle参数中是否有AI功能标志
        if (getArguments() != null && getArguments().containsKey(MainActivity.AI_FUNCTION_KEY)) {
            int functionFlag = getArguments().getInt(MainActivity.AI_FUNCTION_KEY, MainActivity.AI_FUNCTION_NONE);
            
            // 设置一个延迟，等笔记界面加载完成再执行AI功能
            rootView.postDelayed(() -> {
                processAiFunction(functionFlag);
                // 清除标志，避免重复执行
                getArguments().remove(MainActivity.AI_FUNCTION_KEY);
            }, 500); // 延迟500毫秒执行
        }
        
        // 获取当前后退栈条目的SavedStateHandle
        SavedStateHandle savedStateHandle = navController.getCurrentBackStackEntry().getSavedStateHandle();
        
        // 监听AI功能标志的变化
        savedStateHandle.getLiveData(MainActivity.AI_FUNCTION_KEY, MainActivity.AI_FUNCTION_NONE)
            .observe(getViewLifecycleOwner(), functionFlag -> {
                if (functionFlag != null && functionFlag != MainActivity.AI_FUNCTION_NONE) {
                    processAiFunction(functionFlag);
                    // 重置标志，避免重复执行
                    savedStateHandle.set(MainActivity.AI_FUNCTION_KEY, MainActivity.AI_FUNCTION_NONE);
                }
            });
    }

    /**
     * 处理AI功能
     */
    private void processAiFunction(int functionFlag) {
        switch (functionFlag) {
            case MainActivity.AI_FUNCTION_SUMMARY:
                if (!editContent.getText().toString().trim().isEmpty()) {
                    summarizeContent();
                } else {
                    Toast.makeText(requireContext(), "请先输入笔记内容再生成摘要", Toast.LENGTH_SHORT).show();
                }
                break;
            case MainActivity.AI_FUNCTION_OPTIMIZE:
                if (!editContent.getText().toString().trim().isEmpty()) {
                    optimizeNote();
                } else {
                    Toast.makeText(requireContext(), "请先输入笔记内容再进行优化", Toast.LENGTH_SHORT).show();
                }
                break;
            case MainActivity.AI_FUNCTION_KEYPOINTS:
                if (!editContent.getText().toString().trim().isEmpty()) {
                    extractKeyPoints();
                } else {
                    Toast.makeText(requireContext(), "请先输入笔记内容再提取关键点", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private int getCategoryPosition(String category) {
        if (category == null || category.isEmpty()) {
            return 0;
        }
        
        for (int i = 0; i < categories.size(); i++) {
            if (categories.get(i).getName().equals(category)) {
                return i;
            }
        }
        
        return 0; // 默认返回第一个位置
    }

    /**
     * 添加标签
     */
    private void addTag(String tagName) {
        // 检查标签是否已存在
        for (Tag tag : selectedTags) {
            if (tag.getName().equalsIgnoreCase(tagName)) {
                // 标签已存在，不需要重复添加
                return;
            }
        }
        
        // 检查是否在全局标签中存在
        Tag existingTag = null;
        for (Tag tag : availableTags) {
            if (tag.getName().equalsIgnoreCase(tagName)) {
                existingTag = tag;
                break;
            }
        }
        
        if (existingTag != null) {
            // 使用现有标签
            selectedTags.add(existingTag);
        } else {
            // 创建新标签，使用随机颜色
            String[] defaultColors = {"#3F51B5", "#F44336", "#4CAF50", "#FF9800", "#9C27B0", "#03A9F4"};
            int randomIndex = (int) (Math.random() * defaultColors.length);
            Tag newTag = new Tag(tagName, defaultColors[randomIndex]);
            tagViewModel.insert(newTag);
            selectedTags.add(newTag);
        }
        
        // 更新UI
        updateTagChips();
    }
} 